package com.jcark.arch.net

import android.text.TextUtils
import android.util.Log
import com.franmontiel.persistentcookiejar.PersistentCookieJar
import com.franmontiel.persistentcookiejar.cache.SetCookieCache
import com.franmontiel.persistentcookiejar.persistence.SharedPrefsCookiePersistor
import com.google.gson.Gson
import com.google.gson.GsonBuilder
import me.hgj.mvvm.base.appContext
import me.hgj.mvvm.network.BaseNetworkApi
import me.hgj.mvvm.network.interceptor.logging.LogInterceptor
import okhttp3.Cache
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.Response
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.io.File
import java.io.IOException
import java.nio.charset.StandardCharsets
import java.nio.charset.UnsupportedCharsetException
import java.util.concurrent.TimeUnit


class NetworkApi : BaseNetworkApi() {

    companion object {
        val INSTANCE: NetworkApi by lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED) {
            NetworkApi()
        }
    }

    private var mInterceptors: MutableList<Interceptor>? = null
    var requestErrorCallback: RequestErrorCallback? = null

    fun addInterceptors(interceptors: MutableList<Interceptor>?) {
        mInterceptors = interceptors
    }

    override fun setHttpClientBuilder(builder: OkHttpClient.Builder): OkHttpClient.Builder {
        builder.apply {
            //设置缓存配置 缓存最大10M
            cache(Cache(File(appContext.cacheDir, "cxk_cache"), 10 * 1024 * 1024))
            //添加Cookies自动持久化
            cookieJar(cookieJar)
            //添加公共heads 注意要设置在日志拦截器之前，不然Log不会显示head信息
            addInterceptor(MyHeadInterceptor())
            //添加缓存拦截器 可传入缓存天数，不传默认7天
//            addInterceptor(CacheInterceptor())
            // 日志拦截器
            addInterceptor(LogInterceptor())
            addInterceptor(responseInterceptor)

            //其他拦截器
            mInterceptors?.let {
                if (it.size > 0) {
                    for (index in 0 until it.size) {
                        addInterceptor(it[index])
                    }
                }
            }

            //超时时间 连接、读、写
            connectTimeout(30, TimeUnit.SECONDS)
            readTimeout(30, TimeUnit.SECONDS)
            writeTimeout(30, TimeUnit.SECONDS)
        }
        return builder
    }

    //返回数据统一处理操作
    private var responseInterceptor: Interceptor = object : Interceptor {
        @Throws(IOException::class)
        override fun intercept(chain: Interceptor.Chain): Response {
            val utf8 = StandardCharsets.UTF_8
            val request = chain.request()
            // 打印返回报文
            // 先执行请求，才能够获取报文
            val response = chain.proceed(request)
            val responseBody = response.body
            val respBody: String
            if (responseBody != null) {
                val source = responseBody.source()
                source.request(Long.MAX_VALUE)
                val buffer = source.buffer
                var charset = utf8
                val contentType = responseBody.contentType()
                if (contentType != null) {
                    try {
                        charset = contentType.charset(utf8)
                    } catch (e: UnsupportedCharsetException) {
                        e.printStackTrace()
                    }
                }
                respBody = buffer.clone().readString(charset!!)
                Log.d("NET-RESULT", respBody)
                try {
                    if (!TextUtils.isEmpty(respBody)) {
                        val gson = Gson()
                        val baseResponse: BaseApiResponse =
                            gson.fromJson(respBody, BaseApiResponse::class.java)
                        if (baseResponse.status != NetConfigManager.INSTANCE.getSuccessCode()) {
                            requestErrorCallback?.onError(
                                code = baseResponse.status,
                                msg = if (TextUtils.isEmpty(baseResponse.statusDesc)) {
                                    ""
                                } else {
                                    baseResponse.statusDesc
                                }
                            )
                        }
                        return response

                    }
                } catch (e: Exception) {
                    Log.e("Network",e.localizedMessage)
//                    requestErrorCallback?.onError(
//                        code = -1,
//                        msg = e.message.toString()
//                    )

                    return response
                }
            }
            return response
        }
    }

    /**
     * 实现重写父类的setRetrofitBuilder方法，
     * 在这里可以对Retrofit.Builder做任意操作，比如添加GSON解析器，protobuf等
     */
    override fun setRetrofitBuilder(builder: Retrofit.Builder): Retrofit.Builder {
        return builder.apply {
            addConverterFactory(GsonConverterFactory.create(GsonBuilder().create()))
        }
    }

    private val cookieJar: PersistentCookieJar by lazy {
        PersistentCookieJar(SetCookieCache(), SharedPrefsCookiePersistor(appContext))
    }
}
